package com.sg.elb.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sg.common.empty.core.ConditionRes;
import com.sg.common.empty.core.Conditions;
import com.sg.common.empty.service.CfgService;
import com.sg.common.utils.Constant;

@Repository
@Controller
@RequestMapping(value = "/api")
public class ElbApiController {

	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	CfgService service;

	@RequestMapping(value = "/mdm/line/cascader")
	@ResponseBody
	public Object getAddress(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String oransql_idlns = Constant.get(route + ".sql_idlns");
		oransql_idlns = oransql_idlns.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		String res_idlns = Constant.get(route + ".res_idlns");
		List<Map<String, Object>> idlnList = service.queryBySqlToMap(oransql_idlns,
				cr.getParams(), res_idlns.split(","));
		
		String oransql_idsts = Constant.get(route + ".sql_idsts");
		oransql_idsts = oransql_idsts.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);
		String res_idsts = Constant.get(route + ".res_idsts");
		List<Map<String, Object>> idstFullList = service.queryBySqlToMap(oransql_idsts,
				cr.getParams(), res_idsts.split(","));
		
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> lines=new ArrayList<String>();
//		map.put("lines", idlnList);
		for(Map<String,Object> mp:idlnList){
			
			String lindc =(String)mp.get("lindc");
			lines.add(lindc);
			List<Map<String, Object>> idstList = new ArrayList<Map<String, Object>>();
			for(Map<String,Object> idstMap:idstFullList){
				if(StringUtils.equals(lindc, (String)idstMap.get("lindc"))){
					idstList.add(idstMap);
				}
			}
			map.put(lindc, idstList);
		}
		map.put("lines", lines);
		return map;
	}
	}